import { Channels } from '/imports/models/Channels';
import { ChannelMembers } from '/imports/models/ChannelMembers';
import { msg, hideLoading, loading } from '../../components/notice/notice';

Template.channel.onCreated(function () {
  this.ready = new ReactiveVar();
  this.isOwner = new ReactiveVar();
  this.isMember = new ReactiveVar();
  this.channel = new ReactiveVar();

  this.autorun(() => {
    loading({
      content: '欢迎进入，请稍候',
      time: 500
    });
    this.ready.set(false);
    const channelId = Router.current().params.channelId;
    Meteor.call('getChannel', channelId, (err, res) => {
      if (res) {
        this.channel.set(res);
        this.ready.set(true);
      }
    });
  });

  this.autorun(() => {
    const channel = this.channel.get();
    if (channel && channel.name) {
      DocHead.setTitle(`Class / ${channel.name}`);
      this.memberSub = this.subscribe('check.channel.member', channel._id, Meteor.userId());
      if (this.memberSub.ready()) {
        const result = ChannelMembers.find({channel_id: channel._id, user_id: Meteor.userId()});
        if (result.count() === 1) {
          this.isOwner.set(false);
          this.isMember.set(true);
        } else {
          if (channel.owner.id === Meteor.userId()) {
            this.isOwner.set(true);
            this.isMember.set(false);
          } else {
            Router.go('home');
          }
        }
      }
    }
  });
});

Template.channel.onDestroyed(function () {
  if ($('#header').hasClass('bg-primary')) {
    $('#header').removeClass('bg-primary');
  }
});

Template.channel.helpers({
  ready: function () {
    return Template.instance().ready.get();
  },

  channel: function () {
    return Template.instance().channel.get();
  },

  isOwner: function () {
    return Template.instance().isOwner.get();
  },

  isMember: function () {
    return Template.instance().isMember.get();
  }
});